package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.adapter.SysMessageListAdapter;
import com.zhiqianbao.entity.MessageAndPushInfo;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.view.RefreshableView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/2/18.
 */
public class SysMessageMainActivity extends BaseActivity {

    int messageSize = 10;
    /**
     * 是否上拉操作
     */
    boolean isDown = false;
    int isLastisNext = 0;
    RefreshableView refreshableView;
    ListView lvMsg;
    SysMessageListAdapter sysMessageListAdapter;
    Long firstDisplayTime = null;
    TextView systemMsgTv;
    private Result<List> data;
    /**
     * 消息列表显示
     */
    List<MessageAndPushInfo> messageAndPushInfos = new ArrayList<>();

    Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    data = (Result<List>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            try {
                                List<Object> list = data.getData();
                                if (!list.isEmpty()) {
                                    if(list.size()!=0) {
                                        systemMsgTv.setVisibility(View.GONE);
                                        refreshableView.setVisibility(View.VISIBLE);
                                        if (isDown) {
                                            isLastisNext++;
                                        } else {
                                            isLastisNext = 1;
                                            messageAndPushInfos.clear();
                                        }
                                        for (Object obj : list) {
                                            MessageAndPushInfo messageAndPushInfo = gson.fromJson(gson.toJson(obj), MessageAndPushInfo.class);
                                            messageAndPushInfos.add(messageAndPushInfo);
                                        }
                                        if (isDown) {
                                            sysMessageListAdapter.notifyDataSetChanged();
                                        } else {
                                            sysMessageListAdapter = new SysMessageListAdapter(SysMessageMainActivity.this, messageAndPushInfos);
                                            lvMsg.setAdapter(sysMessageListAdapter);
                                            refreshableView.finishRefreshing();
                                        }
                                    }
                                    else{
                                        systemMsgTv.setVisibility(View.VISIBLE);
                                        refreshableView.setVisibility(View.GONE);
                                    }

                                } else {
                                    systemMsgTv.setVisibility(View.VISIBLE);
                                    refreshableView.setVisibility(View.GONE);
                                    refreshableView.finishRefreshing();
                                }
                            } catch (Exception e) {

                            }

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showShortToast1(data.getMsg());
                                }
                            });

                            if (!isDown) {
                                refreshableView.finishRefreshing();
                            }
                        }
                    }
                    break;
            }
            isDown = false;
            closeWaitDialog();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sys_message_main);
        init();
        initView();
    }

    private void initView() {
        refreshableView=(RefreshableView)findViewById(R.id.refreshable_view);
         lvMsg=(ListView)findViewById(R.id.lv_msg);
         systemMsgTv=(TextView)findViewById(R.id.system_msg_tv);
        if (Constants.LOGIN_USER != null) {
            getSysMessages("0", true);
        }

        //添加下拉事件
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                getSysMessages("0", false);
            }
        }, 1);

        //
        lvMsg.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            isDown = true;
                            getSysMessages(isLastisNext + "", true);
                            Log.i(SysMessageMainActivity.class.getSimpleName(), isLastisNext + "");
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
            }
        });

    }

    private void getSysMessages(final String pageNo, boolean dialog) {
        if (dialog) {
            showWaitDialog();
        }
        //调用获取消息接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("size", messageSize + "");
                params.put("pageNo", pageNo);

                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/sysMessage", params, SysMessageMainActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<List> data = Result.fromJson(result, List.class);
                    message.obj = data;
                }
                messageHandler.sendMessage(message);
            }
        }).start();

    }

    @Override
    public void onPause() {
        super.onPause();
        sendRefreshReceiver();
    }

    /**
     * 通知主页面刷新消息提醒
     */
    public void sendRefreshReceiver(){
        Intent intent=new Intent();
        intent.setAction(MainActivity.REFRESH_MSGS);
        sendBroadcast(intent);
    }
}
